package com.blog.auth.controller;

import com.blog.auth.pojo.AuthUser;
import com.blog.auth.service.AuthService;
import com.blog.auth.util.AuthToken;
import com.blog.auth.util.CookieUtil;
import com.blog.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class LoginController {

    //客户端ID
    @Value("${auth.clientId}")
    private String clientId;

    //秘钥
    @Value("${auth.clientSecret}")
    private String clientSecret;

    //Cookie存储的域名
    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    //Cookie生命周期
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    AuthService authService;

    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> formData) {
        try {
            String username = formData.get("username");
            String password = formData.get("password");
            if (StringUtils.isEmpty(username)) {
                throw new RuntimeException("用户名不允许为空");
            }
            if (StringUtils.isEmpty(password)) {
                throw new RuntimeException("密码不允许为空");
            }
            AuthUser authUser = authService.getUsername(username);
            if ("n".equals(authUser.getStatus())) {
                return Result.error("该账号已停用！");
            }
            //申请令牌
            AuthToken authToken = authService.login(username, password, clientId, clientSecret);

            //用户身份令牌
            String access_token = authToken.getAccessToken();
            //将令牌存储到cookie
            saveCookie(access_token);

            // 返回用户信息
            Map<String, Object> map = new HashMap<>();
            map.put("token", authToken);
            map.put("userInfo", authUser);
            return Result.ok("登录成功！", map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("用户名或密码错误！");
        }
    }

    private void saveCookie(String token) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response, cookieDomain, "/", "Authorization", token, cookieMaxAge, false);
    }

    // 获取当前用户信息
    private String getUsername() {
        String username = null;
        // 得到当前认证通过的用户身份
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 用户身份
        Object principal = authentication.getPrincipal();
        if (principal == null) {
            username = "匿名";
        }
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            username = userDetails.getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }
}
